﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;
namespace GameCore
{
    /// <summary>
    /// UI基类,这里会封装很多UI公用的特性
    /// @author:dingjie
    /// </summary>
    public class UIBase : BaseBehaviour
    {
        protected override void Awake() {
            base.Awake();
            InitComponents();
            AddListener();
        }
        protected override void OnDestroy()
        {
            base.OnDestroy();
            RemoveListener();
        }

        /// <summary>
        /// 添加监听，在Awake时调用
        /// </summary>
        protected virtual void AddListener() { }
        /// <summary>
        /// 移除监听，在OnDestroy时调用
        /// </summary>
        protected virtual void RemoveListener() { }
        /// <summary>
        /// 初始化组件，在Awake时调用
        /// </summary>
        protected virtual void InitComponents() { }

#if UNITY_EDITOR
        /// <summary>
        /// 一键引用，不区分大小写
        /// </summary>
        [ContextMenu("一键引用")]
        protected virtual void OnKeyReference()
        {
            //搜索公有、私有、保护类型
            BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            Dictionary<string, Transform> transDic = GetTransforms();
            foreach (var field in this.GetType().GetFields(flags))//.Where(field => field.GetValue(this) == null))
            {
                //私有
                if (field.IsPrivate && !field.IsDefined(typeof(SerializeField), false))
                    continue;
                //保护
                if (!field.IsPrivate && !field.IsPublic && !field.IsDefined(typeof(SerializeField), false))
                    continue;
                Transform trans = null;
                if (transDic.TryGetValue(field.Name.ToLower(), out trans)) {
                    field.SetValue(this, trans.GetComponent(field.FieldType));
                }
            }
        }



        protected Dictionary<string, Transform> GetTransforms()
        {
            Dictionary<string, Transform> transDic = new Dictionary<string, Transform>();
            Transform[] trans = this.transform.GetComponentsInChildren<Transform>(true);
            for (int i = 0; i < trans.Length; i++)
            {
                if (!transDic.ContainsKey(trans[i].name.ToLower())) {
                    transDic.Add(trans[i].name.ToLower(),trans[i]);
                }
            }
            return transDic;
        }
#endif

    }


}

